package com.mc.fastkit.ui

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.mc.fastkit.ext.cast
import java.lang.reflect.ParameterizedType

/**
 * BaseVMActivity
 * @author: MasterChan
 * @date: 2024-04-08 14:23
 */
open class BaseVMActivity<T : ViewBinding, V : BaseViewModel> : BaseVBActivity<T>() {

    protected open val viewModel by lazy { generateViewModel() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(viewModel)
    }

    protected open fun generateViewModel(): V {
        var superClass = javaClass.genericSuperclass
        while (superClass !is ParameterizedType) {
            superClass = (superClass as Class<*>).genericSuperclass
        }
        val vm = superClass.actualTypeArguments[1].cast<Class<V>>()
        return ViewModelProvider(this)[vm]
    }
}